/*
function recurse(t,parent_id,level)
{
	items=t.site.models.Page.List("list_level",{parent_id:parent_id});
	items.forEach(function(p) {p.children=recurse(p.id,level+1);});
	return items;
}*/

exports.add=[
{
	_type:"controller",
	_config_details: {	
	},
	_config: {
		path:"adminpanel/",
		name:"AdminPages",
		admin:1,
		role_code:"pages"
	},
	
	_admin_nav: [
		{section:"contents",name:"Pages",mode:"index"}
	],

	/**
	 * Controller: AdminPages.index 
	 *
	 * Returns:
	 *		HTML
	 */
	index: function(config) {
		//this.items=recurse(this,null,1);
		this.items=this.site.models.Page.ListTree();
		return this.Cview();
	},

	/**
	 * Controller: AdminPages.edit
	 *
	 * Returns:
	 *		HTML
	 */
	edit: function(config) {
		var t=this;
		this.dictionaries={
			templates: this.site.models.Template.List(),
			roles: this.site.models.Role.List(),
			pages: [],
			template_places:{}
		};
		var cpageid=(this.fields.id)?this.fields.id:0;
		function pages_add_level(parent_id,level)
		{
			var arr=t.site.models.Page.List("list_level",{parent_id:parent_id});
			for (var i=0;i<arr.length;i++) {
				var p=arr[i];
				if (p.id==cpageid) continue;
				pages_add_level(p.id,level+1);
				t.dictionaries.pages.push({id:p.id,name:p.alias});
			}
		}
		pages_add_level(null,1);
		var tpts={};
		t.site.models.TemplatePlaceType.List().forEach(function(tpt) { tpts[tpt.id]=tpt;});
		t.site.models.Template.List().forEach(function(tmpl) {
			var tps=t.dictionaries.template_places[tmpl.id]=[];
			t.site.models.TemplatePlace.List("list_of_template",{template_id:tmpl.id}).forEach(function(tp) {
				var hh={place_type_code:tpts[tp.place_type_id].code,place_type_name:tpts[tp.place_type_id].name};
				["place_type_id","code","name","admin_height","templatewide","preprocess"].forEach(function(k) {hh[k]=tp[k];});
				tps.push(hh);
			});
		});
		if (this.fields.id) {
			this.cpage=this.site.models.Page.Get(this.fields.id);
		} else {
			this.cpage=this.site.models.Page.Create();
		}
		this.cpage.FetchLocales();
		this.F("Admin","load_l10ns");
		t.cpage_blocks={};
		t.site.sql.execute_and_fetch("page_blocks/list_of_page",{page_id:this.fields.id}).forEach(function(pb) {
			if (!t.cpage_blocks[pb.l10n_id]) t.cpage_blocks[pb.l10n_id]={};
			t.cpage_blocks[pb.l10n_id][pb.template_place_code]=pb.body;
		});
		return this.Cview();
	},

	/**
	 * Controller: AdminPages.save
	 *
	 * Returns:
	 *		JSON Object
	 */
	save: function(config) {
		var t=this;
		var item;
		var old_template_id=0;
		if (this.fields.id) {
			item=this.site.models.Page.Get(this.fields.id);
			old_template_id=item.template_id;
		} else {
			item=this.site.models.Page.Create();
		}
		item.FetchLocales();
		item.ApplyAdminFields(this.fields);
		item.SaveAll();
		var pbs_old={};

		// TODO mediums
		t.site.sql.execute_and_fetch("page_blocks/list_of_page",{page_id:this.fields.id}).forEach(function(pb) {
			pbs_old["block_"+pb.l10n_id+"__"+pb.medium_id+"__"+pb.template_place_code]=pb.id;
		});
		for (var k in this.fields) {
			var arr=k.match(/^block_(\d+)__(\d+)__(.+)$/);
			if (!arr) continue;	
			if (pbs_old[k] && old_template_id==item.template_id) {
				this.site.sql.execute("page_blocks/update",{body:this.fields[k],id:pbs_old[k]});
				delete pbs_old[k];
			} else {
				this.site.sql.execute("page_blocks/insert",{body:this.fields[k],page_id:item.id,l10n_id:arr[1],template_place_code:arr[3],medium_id:arr[2],template_id:item.template_id});
			}
		}
		for (var k in pbs_old) this.site.sql.execute("page_blocks/delete",{id:pbs_old[k]});
		if (this.fields.save_only) return JSON.stringify({call:"ajajform_frm_set_id",name:"id",id:item.id});
		return JSON.stringify({redirect:{url:this.action}});
	},

	/**
	 * Controller: AdminPages.index_recurse_helper
	 */
	index_recurse_helper: function() {
		if (this.item.children.length==0) return "";
		var item=this.item;
		this.items=item.children;
		var r=this.Cview();
		this.item=item;
		return r;
	},

	/**
	 * Controller: AdminPages.reorder
	 */
	reorder: function(config) {
		var t=this;
		var pages=[];
		var page_orders=[];
		this.fields.pages.split(/,/).forEach(function(page_id) {
			page_id=page_id.replace(/page-/,'');
			pages.push(page_id);
			var ord=t.site.sql.execute_and_fetch_one("pages/get_ordering",{page_id:page_id})["ordering"]*1;
			page_orders.push(ord);
			t.site.sql.execute("pages/set_ordering",{page_id:page_id,ordering:-ord});
		});
		page_orders.sort(function(a,b){return a - b});
		var i=0;
		var r={orderings:{},pages:[]};
		pages.forEach(function(page_id) {
			r.pages.push(page_id);
			r.orderings[page_id]=page_orders[i];
			t.site.sql.execute("pages/set_ordering",{page_id:page_id,ordering:page_orders[i]});
			i++;
		});
		//throw space.Dumper({pages:pages,page_orders:page_orders,r:r});
		return JSON.stringify(r);
	},

	/**
	 * Controller: AdminPages.delete
	 */
	"delete": function(config) {
		var t=this;
		this.cpage=this.site.models.Page.Get(this.fields.id);
		this.cpage.FetchLocales();
		this.F("Admin","load_l10ns");
		return this.Cview();
	},

	/**
	 * Controller: AdminPages.delete2
	 *
	 * Returns:
	 *		JSON Object
	 */
	delete2: function(config) {
		var t=this;
		item=this.site.models.Page.Get(this.fields.id);
		t.site.sql.execute_and_fetch("page_blocks/list_of_page",{page_id:this.fields.id}).forEach(function(pb) {
			t.site.sql.execute("page_blocks/delete",{id:pb.id});
		});
		item.FetchLocales();
		item.ApplyAdminFields(this.fields);
		item.Delete();
		return JSON.stringify({redirect:{url:this.action}});
	},

	/**
	 * Controller: AdminPages.translit
	 *
	 */
	translit: function(config) {
		return this.F("Languages","to_code",this.fields.value);
	}

}];

